# Route for private chat
from flask_socketio import SocketIO, emit, join_room
from models import *
from flask import *
from flask_login import *

def _private_chat(recipient):
    recipient_user = User.query.filter_by(username=recipient).first()
    if not recipient_user or recipient_user.id == current_user.id:
        flash('Invalid recipient')
        return redirect(url_for('home'))
    return render_template('private_chat.html', recipient=recipient)

def _handle_message(data):
    emit('receive_message', {'username': current_user.username, 'message': data}, broadcast=True)

def _handle_private_message(data):
    recipient_username = data.get('recipient')
    message = data.get('message')
    recipient = User.query.filter_by(username=recipient_username).first()
    if recipient:
        # Save the message to the database
        new_message = Message(
            sender_id=current_user.id,
            recipient_id=recipient.id,
            content=message
        )
        db.session.add(new_message)
        db.session.commit()

        # Create a unique room for the sender and recipient
        room = f"private_{min(current_user.id, recipient.id)}_{max(current_user.id, recipient.id)}"

        # Emit to the room
        emit('receive_private_message', {
            'sender': current_user.username,
            'message': message,
            'timestamp': new_message.timestamp.isoformat()
        }, room=room)
    else:
        emit('error', {'message': 'Recipient not found'}, to=request.sid)

def _chat_history(recipient):
    recipient_user = User.query.filter_by(username=recipient).first()
    if not recipient_user:
        return jsonify({'error': 'Recipient not found'}), 404

    messages = Message.query.filter(
        ((Message.sender_id == current_user.id) & (Message.recipient_id == recipient_user.id)) |
        ((Message.sender_id == recipient_user.id) & (Message.recipient_id == current_user.id))
    ).order_by(Message.timestamp).all()

    return jsonify([{
        'sender': User.query.get(msg.sender_id).username,
        'content': msg.content,
        'timestamp': msg.timestamp.isoformat()
    } for msg in messages])

def _join_private_room(data):
    recipient_username = data.get('recipient')
    recipient = User.query.filter_by(username=recipient_username).first()
    if recipient:
        # Create a unique room for the sender and recipient
        room = f"private_{min(current_user.id, recipient.id)}_{max(current_user.id, recipient.id)}"
        join_room(room)
    else:
        emit('error', {'message': 'Recipient not found'}, to=request.sid)

def _on_join():
    join_room(current_user.id)  # Join a room named after the user's ID

def _unread_messages():
    messages = Message.query.filter_by(recipient_id=current_user.id, is_read=False).all()
    for message in messages:
        message.is_read = True  # Mark messages as read
    db.session.commit()
    return {'messages': [{'sender': User.query.get(msg.sender_id).username, 'content': msg.content, 'timestamp': msg.timestamp} for msg in messages]}

def _chat_list():
    return render_template('chat_list.html',users=User.query.all())
